import fsp from "node:fs/promises";
import path from "node:path";
import fs from "node:fs";
import type { LocalProjectItem } from "@common/local-project.types.ts";

export async function scanProjects(parent: LocalProjectItem, excludes: Record<string, number>) {
  const projects: LocalProjectItem[] = [];
  const files = await fsp.readdir(parent.path, { withFileTypes: true });
  for (const it of files) {
    if (excludes[it.name] || it.name.startsWith(".")) continue;
    if (it.isDirectory()) {
      // 判断nodejs项目
      const fullPath = path.join(parent.path, it.name);
      const packageJsonFile = path.join(fullPath, "package.json");
      if (fs.existsSync(packageJsonFile)) {
        projects.push({ key: fullPath, title: it.name, path: fullPath, type: "nodejs" });

        // 再判断是不是react-native项目,找出安卓模块
        const androidModule = path.join(fullPath, "android");
        if (fs.existsSync(path.join(androidModule, "gradle"))) {
          projects.push({ key: androidModule, title: `${it.name}/android`, path: androidModule, type: "android" });
        }
        continue;
      }

      // android
      const androidModule = path.join(fullPath, "app/src/main/AndroidManifest.xml");
      if (fs.existsSync(androidModule)) {
        projects.push({ key: fullPath, title: it.name, path: fullPath, type: "android" });
        continue;
      }

      // flutter
      const flutterModule = path.join(fullPath, "pubspec.yaml");
      if (fs.existsSync(flutterModule)) {
        projects.push({ key: fullPath, title: it.name, path: fullPath, type: "flutter" });
        continue;
      }

      // java-maven项目
      const pomFile = path.join(fullPath, "pom.xml");
      if (fs.existsSync(pomFile)) {
        projects.push({ key: fullPath, title: it.name, path: fullPath, type: "java" });
        continue;
      }
      // java-gradle项目
      if (fs.existsSync(path.join(fullPath, "build.gradle")) || fs.existsSync(path.join(fullPath, "build.gradle.kts"))) {
        projects.push({ key: fullPath, title: it.name, path: fullPath, type: "java" });
        continue;
      }

      // python项目
      const pyFile = path.join(fullPath, "pyproject.toml");
      const requirementsFile = path.join(fullPath, "requirements.txt");
      if (fs.existsSync(pyFile) || fs.existsSync(requirementsFile)) {
        projects.push({ key: fullPath, title: it.name, path: fullPath, type: "python" });
        continue;
      }

      // .net
      const subFiles = (await fsp.readdir(fullPath, { withFileTypes: true })).filter(it => it.isFile());
      const dotnetProjectFile = subFiles.find(it => it.name.endsWith(".sln")) || subFiles.find(it => it.name.endsWith(".csproj"));
      if (dotnetProjectFile) {
        const dotnetProjectFilePath = path.join(fullPath, dotnetProjectFile.name);
        projects.push({
          key: dotnetProjectFilePath,
          title: [it.name, dotnetProjectFile.name].join("/"),
          path: dotnetProjectFilePath,
          type: "dotnet",
        });
        continue;
      }

      // go
      const goModule = path.join(fullPath, "go.mod");
      if (fs.existsSync(goModule)) {
        projects.push({ key: fullPath, title: it.name, path: fullPath, type: "go" });
        continue;
      }

      // rust
      const rustModule = path.join(fullPath, "Cargo.toml");
      if (fs.existsSync(rustModule)) {
        projects.push({ key: fullPath, title: it.name, path: fullPath, type: "rust" });
        continue;
      }

      // php
      const phpModule = path.join(fullPath, "index.php");
      if (fs.existsSync(phpModule)) {
        projects.push({ key: fullPath, title: it.name, path: fullPath, type: "php" });
        continue;
      }

      // 递归扫描子项目
      const sub: LocalProjectItem = { key: fullPath, title: it.name, path: fullPath };
      await scanProjects(sub, excludes);
      if (existsProject(sub)) {
        projects.push(sub);
      }
    }
  }

  parent.children = projects;
}

const existsProject = (item: LocalProjectItem) => {
  if (!!item.type) return true;
  if (item.children) {
    for (const child of item.children) {
      if (existsProject(child)) {
        return true;
      }
    }
  }
  return false;
};

/**
 * 将只有一个子节点的节点，合并到父节点
 * @param parent
 */
export function mergeSingleNode(parent: LocalProjectItem) {
  if (parent.children) {
    for (const child of parent.children) {
      mergeSingleNode(child);
    }

    if (parent.children.length === 1) {
      const child = parent.children[0];
      parent.key = child.key;
      parent.title = [parent.title, child.title].join("/");
      parent.path = child.path;
      parent.type = child.type;
      parent.children = child.children;
    }
  }
}
